package com.gemserk.infraestructure.lwjglmavenizer

import groovyx.net.http.HTTPBuilder;

import java.io.File;

class HTTPDownloader {
	static def downloadFile(HTTPBuilder httpbuilder, def fileUri, File destFile){
		println "Downloading uri: $fileUri"
		return httpbuilder.request(fileUri,groovyx.net.http.Method.GET,groovyx.net.http.ContentType.BINARY) { req ->
			headers.'User-Agent' = 'curl/7.19.7 (i486-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15'
			
			response.success = { resp, InputStream reader ->
				assert resp.statusLine.statusCode == 200
				println "My response handler got response: ${resp.statusLine}"
				long fileLength = Long.parseLong(resp.headers.'Content-Length')
				println "Response length: ${fileLength/(1024)}kB"
				
				destFile.withOutputStream {OutputStream outputStream ->
					byte[] buffer = new byte[100000]
					int downloaded = 0
					
					int chunkSize = 0
					boolean done = false
					int time = System.currentTimeMillis()
					int lastDownloaded = 0
					while((chunkSize = reader.read(buffer))!=-1){
						outputStream.write(buffer, 0, chunkSize)
						
						downloaded+=chunkSize
						def percent = (downloaded/fileLength)*100
						if(percent == 100){
							println "Done downloading ${destFile.getName()}"
						} else {
							int currentTime = System.currentTimeMillis()
							int lastTimePeriod = currentTime - time
							if(lastTimePeriod > 1000){
								int downloadedInTimePeriod = (downloaded - lastDownloaded)/1024
								int speed = (downloadedInTimePeriod / lastTimePeriod)*1000
								println "Downloaded ${percent}% - speed: $speed kB/s - ${destFile.getName()}"
								lastDownloaded = downloaded
								time = currentTime
							}
						}
						
					}
				}
			}
			
			// called only for a 401 (access denied) status code:
			response.'404' = { resp -> println 'Not found' }
		}
	}
}
